package com.example.safeassistan.hiddendanger.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.example.safeassistan.R;
import com.example.safeassistan.base.BaseActivity;
import com.example.safeassistan.base.BaseModel;
import com.example.safeassistan.common.UserData;
import com.example.safeassistan.constants.UrlConstants;
import com.example.safeassistan.hiddendanger.model.HiddenDangerDetailModel;
import com.example.safeassistan.home.activity.ActivityHiddenDangerType;
import com.example.safeassistan.home.activity.AuthorizeDepartMentPerson;
import com.example.safeassistan.home.activity.AuthorizeDepartment;
import com.example.safeassistan.home.activity.HiddenDanger_Level_Select;
import com.example.safeassistan.home.activity.HiddendangerReform;
import com.example.safeassistan.home.adapter.ImageListAdapter;
import com.example.safeassistan.http.HttpRequest;
import com.example.safeassistan.http.HttpStringCallBack;
import com.example.safeassistan.main.MainActivity;
import com.example.safeassistan.utile.GlideEngine;
import com.example.safeassistan.utile.JsonUtils;
import com.example.safeassistan.utile.ToastUtil;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class HiddendangerUnSubmit extends BaseActivity implements View.OnClickListener {
    private TextView tvAssess,tvReform,tvHiddendDanger,tvAsseessDepart,tvAssessPerson,tvReformDate,tvHiddenLevel,tvCancle,
            tvSubmit,tvSubmit1,tvHiddendDangerType;
    private LinearLayout llSelectType,llAssessInfo,llReform,llBottom;
    private EditText etRemark,etHiddendDangerName,etPrice,etReason,etReformMethod;
    private LinearLayout llAssessDepart,llAssessPerson,llReformDate,llHiddenLevel,llHiddendangerType,llReformInfo;

    private LinearLayout llReformDepart,llReformPerson,llAcceptDepart,llAcceptPerson,llReformDate1;
    private TextView tvReformDepart,tvReformPerson,tvAcceptDepart,tvAcceptPerson,tvReformDate1;

    private TextView tvResultTitle;
    private LinearLayout llResultTitle;

    private RecyclerView rcPic;//图片列表
    private static final Integer REQUESTCODE=10001;
    private static final Integer REQUESTCODE2=10002;
    private static final Integer REQUESTCODE1=10000;
    private static final Integer REQUESTCODE3=10003;
    private static final Integer REQUESTCODE4=10004;
    private static final Integer REQUESTCODE5=10005;
    private static final Integer REQUESTCODE6=10006;
    private static final Integer REQUESTCODE7=10007;

    private HiddenDangerDetailModel model;
    private String remark="";//备注
    private String hiddenId="";//隐患i d
    private String hiddendangerLevel="3";//隐患等级  //3  一般 1重大
    private String hdangerType="";//隐患类型
    private String hdangerTitle="";//隐患标题
    private String hdangerImg="";//现场隐患照片
    private String isCommit="1";//是否提交 0暂存 1提交
    private String isReview="0";//0 评审 1立即整改
    private String rectImg="";//整改附件
    private String rectMeasures="";//整改措施
    private String rectPrice="";//整改金额
    private String rectReason="";//整改原因
    private String reviewDepartId="";//评审部门
    private String reviewPersonId="";//评审人员
    private String reviewTime="";//评审时间
    private String riskPointId="";//风险点id
    private String rectDepartId="";//整改部门id
    private String rectPersonId="";//整改人员id
    private String acceptDepartId="";//验收部门id
    private String acceptPersonId="";//验收人员id
    private String allottedTime="";//整改期限


    private HiddenDangerImageAdapter adapter;
    private ArrayList<String> imagesUrl;
    private RecyclerView.LayoutManager managers;


    private int isFirstadd=0;//0第一次创建 1 重新提交


    public static void actionStart(Context context,String hiddenId,String riskPointId,int isFirstadd) {
        Intent intent = new Intent(context, HiddendangerUnSubmit.class);
        intent.putExtra("hiddenId",hiddenId);
        intent.putExtra("riskPointId",riskPointId);
        intent.putExtra("isFirstadd",isFirstadd);
        context.startActivity(intent);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tvHiddendDanger:
                //存在隐患   双击出现选项
                doubleClick();
                break;
            case R.id.tvReform:
                //立即整改
                reSetResult();
                isReview="1";
                tvReform.setTextColor(getResources().getColor(R.color.blue_3B5BEA));
                tvReform.setBackgroundResource(R.drawable.stoke_solid_blue_bg_5);
                llAssessInfo.setVisibility(View.GONE);
                llReform.setVisibility(View.VISIBLE);
                llBottom.setVisibility(View.GONE);
                break;
            case R.id.tvAssess:
                //评审
                reSetResult();
                isReview="0";
                tvAssess.setTextColor(getResources().getColor(R.color.blue_3B5BEA));
                tvAssess.setBackgroundResource(R.drawable.stoke_solid_blue_bg_5);
                llAssessInfo.setVisibility(View.VISIBLE);
                llReform.setVisibility(View.GONE);
                llBottom.setVisibility(View.VISIBLE);
                break;
            case R.id.llReformDepart:
                //整改部门
                Intent intent4=new Intent(HiddendangerUnSubmit.this, AuthorizeDepartment.class);
                intent4.putExtra("flag", REQUESTCODE4);
                startActivityForResult(intent4, REQUESTCODE4);
                break;
            case R.id.llAcceptDepart:
                //验收部门
                Intent intent6=new Intent(HiddendangerUnSubmit.this, AuthorizeDepartment.class);
                intent6.putExtra("flag", REQUESTCODE6);
                startActivityForResult(intent6, REQUESTCODE6);
                break;
            case R.id.llAssessDepart:
                //评审部门
                Intent intent=new Intent(HiddendangerUnSubmit.this, AuthorizeDepartment.class);
                intent.putExtra("flag", REQUESTCODE);
                startActivityForResult(intent, REQUESTCODE);
                break;
            case R.id.llAssessPerson:
                //评审人
                if (reviewDepartId.equals("")){
                    //没有选择评审部门
                    Toast.makeText(HiddendangerUnSubmit.this,"请先选择评审部门!!!",Toast.LENGTH_SHORT).show();
                    return;
                }else {
                    Intent intent1=new Intent(HiddendangerUnSubmit.this, AuthorizeDepartMentPerson.class);
                    intent1.putExtra("flag", REQUESTCODE1);
                    intent1.putExtra("defectId",reviewDepartId);
                    startActivityForResult(intent1, REQUESTCODE1);
                }
                break;
            case R.id.llReformPerson:
                //整改人
                if (rectDepartId.equals("")){
                    Toast.makeText(HiddendangerUnSubmit.this,"请先选择整改部门!!!",Toast.LENGTH_SHORT).show();
                    return;
                }else {
                    Intent intent5=new Intent(HiddendangerUnSubmit.this, AuthorizeDepartMentPerson.class);
                    intent5.putExtra("flag", REQUESTCODE5);
                    intent5.putExtra("defectId",rectDepartId);
                    startActivityForResult(intent5, REQUESTCODE5);
                }
                break;
            case R.id.llAcceptPerson:
                //验收人
                if (acceptDepartId.equals("")){
                    Toast.makeText(HiddendangerUnSubmit.this,"请先选择验收部门!!!",Toast.LENGTH_SHORT).show();
                    return;
                }else {
                    Intent intent7=new Intent(HiddendangerUnSubmit.this, AuthorizeDepartMentPerson.class);
                    intent7.putExtra("flag", REQUESTCODE7);
                    intent7.putExtra("defectId",acceptDepartId);
                    startActivityForResult(intent7, REQUESTCODE7);
                }
                break;

            case R.id.llReformDate:
                //评审日期
                TimePickerView startTime = new TimePickerBuilder(HiddendangerUnSubmit.this, new OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {//选中事件回调
                        Calendar calendar=Calendar.getInstance();
                        calendar.setTime(date);
                        SimpleDateFormat sf=new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
                        reviewTime=sf.format(date);
                        tvReformDate.setText(sf.format(date));
                    }
                })
                        .setType(new boolean[]{true, true, true, false, false, false})// 默认全部显示
                        .setCancelText("取消")//取消按钮文字
                        .isDialog(true)
                        .setSubmitText("确定")//确认按钮文字
                        .setTitleSize(18)//标题文字大小
                        .setTitleColor(getResources().getColor(R.color.white))
                        .setTitleText("整改日期")
                        .setContentTextSize(17)
                        .setOutSideCancelable(true)//点击屏幕，点在控件外部范围时，是否取消显示
                        .isCyclic(true)//是否循环滚动
                        .setTextColorOut(getResources().getColor(R.color.gray6))
                        .setTextColorCenter(getResources().getColor(R.color.blue_3B5BEA))
                        .setSubmitColor(getResources().getColor(R.color.white))//确定按钮文字颜色
                        .setLabel("年", "月", "日", "时", "分", "秒")//默认设���为年月日时分秒
                        .isCenterLabel(false) //是否只显示中间选中项的 label 文字，false 则每项 item 全部都带有 label。
                        .build();
                startTime.show();
                break;
            case R.id.llReformDate1:
                //整改日期
                TimePickerView startTime1 = new TimePickerBuilder(HiddendangerUnSubmit.this, new OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {//选中事件回调
                        Calendar calendar=Calendar.getInstance();
                        calendar.setTime(date);
                        SimpleDateFormat sf=new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
                        allottedTime=sf.format(date);
                        tvReformDate1.setText(sf.format(date));
                    }
                })
                        .setType(new boolean[]{true, true, true, false, false, false})// 默认全部显示
                        .setCancelText("取消")//取消按钮文字
                        .isDialog(true)
                        .setSubmitText("确定")//确认按钮文字
                        .setTitleSize(18)//标题文字大小
                        .setTitleColor(getResources().getColor(R.color.white))
                        .setTitleText("整改日期")
                        .setContentTextSize(17)
                        .setOutSideCancelable(true)//点击屏幕，点在控件外部范围时，是否取消显示
                        .isCyclic(true)//是否循环滚动
                        .setTextColorOut(getResources().getColor(R.color.gray6))
                        .setTextColorCenter(getResources().getColor(R.color.blue_3B5BEA))
                        .setSubmitColor(getResources().getColor(R.color.white))//确定按钮文字颜色
                        .setLabel("年", "月", "日", "时", "分", "秒")//默认设���为年月日时分秒
                        .isCenterLabel(false) //是否只显示中间选中项的 label 文字，false 则每项 item 全部都带有 label。
                        .build();
                startTime1.show();
                break;
            case R.id.llHiddenLevel:
                //隐患等级
                Intent intent2=new Intent(HiddendangerUnSubmit.this, HiddenDanger_Level_Select.class);
                intent2.putExtra("flag", REQUESTCODE2);
                startActivityForResult(intent2, REQUESTCODE2);
                break;
            case R.id.tvCancle:
                //撤销隐患
                if (isFirstadd==0){//第一次创建 是暂存
                    isCommit="0";
                    if (hdangerType.equals("")){
                        Toast.makeText(HiddendangerUnSubmit.this,"请选择隐患类型！！",Toast.LENGTH_SHORT).show();
                        return;
                    }

                    if (hiddendangerLevel!=null&&hiddendangerLevel.equals("")){
                        Toast.makeText(HiddendangerUnSubmit.this,"请选择隐患等级！！",Toast.LENGTH_SHORT).show();
                        return;
                    }

                    if (hdangerTitle.equals("")){
                        Toast.makeText(HiddendangerUnSubmit.this,"请填写隐患标题！！",Toast.LENGTH_SHORT).show();
                        return;
                    }

                    //附件必须上传
                    if (imagesUrl.size()<=0){
                        Toast.makeText(HiddendangerUnSubmit.this,"请至少上传一个附件！！",Toast.LENGTH_SHORT).show();
                        return;
                    }

                    if (isReview.equals("0")) {
                        //评审
                        if (reviewDepartId.equals("")) {
                            Toast.makeText(HiddendangerUnSubmit.this, "请选择评审部门！！", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        if (reviewPersonId.equals("")) {
                            Toast.makeText(HiddendangerUnSubmit.this, "请选择评审人员！！", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        if (reviewTime.equals("")) {
                            Toast.makeText(HiddendangerUnSubmit.this, "请选择评审日期！！", Toast.LENGTH_SHORT).show();
                            return;
                        }
                    }

                    if (UserData.create(HiddendangerUnSubmit.this).get(UserData.ls_ps).equals("0")){
                        //正常
                        if (!rectDepartId.equals("")){
                            Toast.makeText(HiddendangerUnSubmit.this, "请选择整改部门！！", Toast.LENGTH_SHORT).show();
                            return;
                        }

                        if (!rectPersonId.equals("")){
                            Toast.makeText(HiddendangerUnSubmit.this, "请选择整改人！！", Toast.LENGTH_SHORT).show();
                            return;
                        }

                        if (!acceptPersonId.equals("")){
                            Toast.makeText(HiddendangerUnSubmit.this, "请选择验收人！！", Toast.LENGTH_SHORT).show();
                            return;
                        }

                        if (!acceptDepartId.equals("")){
                            Toast.makeText(HiddendangerUnSubmit.this, "请选择验收部门！！", Toast.LENGTH_SHORT).show();
                            return;
                        }

                        if (!allottedTime.equals("")){
                            Toast.makeText(HiddendangerUnSubmit.this, "请选择整改日期！！", Toast.LENGTH_SHORT).show();
                            return;
                        }
                    }

                    if (hdangerImg.contains("shaungyufang.oss-cn-beijing.aliyuncs.com")){
                        submitData();
                    }else {
                        uploadImg(imagesUrl.get(0));
                    }
                }else {
                    hiddenRepair();
                }
                break;
            case R.id.llHiddendangerType:
                //隐患类型
                Intent intent1=new Intent(HiddendangerUnSubmit.this, ActivityHiddenDangerType.class);
                intent1.putExtra("flag", REQUESTCODE3);
                startActivityForResult(intent1, REQUESTCODE3);
                break;
            case R.id.tvSubmit:
            case R.id.tvSubmit1:
                if (remark.equals("")){
                    Toast.makeText(HiddendangerUnSubmit.this,"请填写备注信息！！",Toast.LENGTH_SHORT).show();
                    return;
                }

                if (hdangerType.equals("")){
                    Toast.makeText(HiddendangerUnSubmit.this,"请选择隐患类型！！",Toast.LENGTH_SHORT).show();
                    return;
                }

                if (hiddendangerLevel!=null&&hiddendangerLevel.equals("")){
                    Toast.makeText(HiddendangerUnSubmit.this,"请选择隐患等级！！",Toast.LENGTH_SHORT).show();
                    return;
                }

                if (hdangerTitle.equals("")){
                    Toast.makeText(HiddendangerUnSubmit.this,"请填写隐患标题！！",Toast.LENGTH_SHORT).show();
                    return;
                }


                if (imagesUrl.size()<1){
                    Toast.makeText(HiddendangerUnSubmit.this,"请至少上传一个附件！！",Toast.LENGTH_SHORT).show();
                    return;
                }


                if (UserData.create(HiddendangerUnSubmit.this).get(UserData.ls_ps).equals("0")){
                    //正常
                    if (rectDepartId.equals("")){
                        Toast.makeText(HiddendangerUnSubmit.this, "请选择整改部门！！", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    if (rectPersonId.equals("")){
                        Toast.makeText(HiddendangerUnSubmit.this, "请选择整改人！！", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    if (acceptPersonId.equals("")){
                        Toast.makeText(HiddendangerUnSubmit.this, "请选择验收人！！", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    if (acceptDepartId.equals("")){
                        Toast.makeText(HiddendangerUnSubmit.this, "请选择验收部门！！", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    if (allottedTime.equals("")){
                        Toast.makeText(HiddendangerUnSubmit.this, "请选择整改日期！！", Toast.LENGTH_SHORT).show();
                        return;
                    }
                }else {
                    if (isReview.equals("0")) {
                        //评审
                        if (reviewDepartId.equals("")) {
                            Toast.makeText(HiddendangerUnSubmit.this, "请选择评审部门！！", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        if (reviewPersonId.equals("")) {
                            Toast.makeText(HiddendangerUnSubmit.this, "请选择评审人员！！", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        if (reviewTime.equals("")) {
                            Toast.makeText(HiddendangerUnSubmit.this, "请选择评审日期！！", Toast.LENGTH_SHORT).show();
                            return;
                        }
                    }
                }

                if (hdangerImg.contains("shaungyufang.oss-cn-beijing.aliyuncs.com")){
                    submitData();
                }else {
                    uploadImg(imagesUrl.get(0));
                }
                break;
        }
    }

    private Handler handler;
    private int clickCount=0;
    private void doubleClick() {
        clickCount++;
        handler=new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if(clickCount==2){
                    //双击
                    llSelectType.setVisibility(View.VISIBLE);
                }
                handler.removeCallbacksAndMessages(null);
                //清空handler延时，并防内存泄漏
                clickCount = 0;//计数清零
            }
        },500);//延时timeout后执行run方法中的代码
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        setAndroidNativeLightStatusBar(true);
    }

    @Override
    protected int setLayoutResourceID() {
        return R.layout.hiddendanger_add;
    }

    @Override
    protected void initView() {
        setTitleText("添加隐患");
        riskPointId=getIntent().getStringExtra("riskPointId");
        hiddenId=getIntent().getStringExtra("hiddenId");
        isFirstadd=getIntent().getIntExtra("isFirstadd",0);
        llSelectType=findViewById(R.id.llSelectType);
        tvReform=findViewById(R.id.tvReform);
        tvAssess=findViewById(R.id.tvAssess);
        tvHiddendDanger=findViewById(R.id.tvHiddendDanger);
        llAssessInfo=findViewById(R.id.llAssessInfo);
        llReform=findViewById(R.id.llReform);
        llBottom=findViewById(R.id.llBottom);
        etRemark=findViewById(R.id.etRemark);
        llReformDepart=findViewById(R.id.llReformDepart);
        rcPic=findViewById(R.id.rcPic);
        tvReformPerson=findViewById(R.id.tvReformPerson);
        llReformPerson=findViewById(R.id.llReformPerson);
        llAcceptPerson=findViewById(R.id.llAcceptPerson);
        tvResultTitle=findViewById(R.id.tvResultTitle);
        tvAcceptPerson=findViewById(R.id.tvAcceptPerson);
        tvReformDate1=findViewById(R.id.tvReformDate1);
        etHiddendDangerName=findViewById(R.id.etHiddendDangerName);
        tvHiddendDangerType=findViewById(R.id.tvHiddendDangerType);
        llHiddenLevel=findViewById(R.id.llHiddenLevel);
        llAcceptDepart=findViewById(R.id.llAcceptDepart);
        llReformInfo=findViewById(R.id.llReformInfo);
        tvReformDate=findViewById(R.id.tvReformDate);
        tvAssessPerson=findViewById(R.id.tvAssessPerson);
        tvAsseessDepart=findViewById(R.id.tvAsseessDepart);
        llAssessDepart=findViewById(R.id.llAssessDepart);
        llAssessPerson=findViewById(R.id.llAssessPerson);
        llReformDate=findViewById(R.id.llReformDate);
        llReformDate1=findViewById(R.id.llReformDate1);
        tvHiddenLevel=findViewById(R.id.tvHiddenLevel);
        etReformMethod=findViewById(R.id.etReformMethod);
        tvCancle=findViewById(R.id.tvCancle);
        tvReformDepart=findViewById(R.id.tvReformDepart);
        llResultTitle=findViewById(R.id.llResultTitle);
        tvSubmit1=findViewById(R.id.tvSubmit1);
        tvAcceptDepart=findViewById(R.id.tvAcceptDepart);
        tvSubmit=findViewById(R.id.tvSubmit);
        etPrice=findViewById(R.id.etPrice);
        llHiddendangerType=findViewById(R.id.llHiddendangerType);
        etReason=findViewById(R.id.etReason);
        llHiddendangerType.setOnClickListener(this::onClick);
        tvCancle.setOnClickListener(this::onClick);
        llHiddenLevel.setOnClickListener(this::onClick);
        llReformDepart.setOnClickListener(this::onClick);
        tvSubmit.setOnClickListener(this::onClick);
        llReformDate.setOnClickListener(this::onClick);
        llAcceptPerson.setOnClickListener(this::onClick);
        llAcceptDepart.setOnClickListener(this::onClick);
        llAssessPerson.setOnClickListener(this::onClick);
        llAssessDepart.setOnClickListener(this::onClick);
        tvSubmit1.setOnClickListener(this::onClick);
        tvHiddendDanger.setOnClickListener(this::onClick);
        llReformDate1.setOnClickListener(this::onClick);
        tvAssess.setOnClickListener(this::onClick);
        tvReform.setOnClickListener(this::onClick);
        llReformPerson.setOnClickListener(this::onClick);
        etRemark.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                remark=s.toString().trim();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        etHiddendDangerName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                hdangerTitle=s.toString().trim();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        etPrice.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                rectPrice=s.toString().trim();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        etReason.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                rectReason=s.toString().trim();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        etReformMethod.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                rectMeasures=s.toString().trim();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        if (isFirstadd==0){
            tvCancle.setText("暂存");
            llResultTitle.setVisibility(View.GONE);
            tvResultTitle.setVisibility(View.GONE);
            llSelectType.setVisibility(View.VISIBLE);
        }else {
            tvCancle.setText("撤销");
            llResultTitle.setVisibility(View.VISIBLE);
            tvResultTitle.setVisibility(View.VISIBLE);
            getDetail();
        }

        if (UserData.create(HiddendangerUnSubmit.this).get(UserData.ls_ps).equals("1")){
            //1 正常流程
            llAssessInfo.setVisibility(View.VISIBLE);
            llSelectType.setVisibility(View.VISIBLE);
            tvResultTitle.setVisibility(View.VISIBLE);
            llResultTitle.setVisibility(View.VISIBLE);
            llReformInfo.setVisibility(View.GONE);
        }else {
            //0 直接整改验收
            llAssessInfo.setVisibility(View.GONE);
            llSelectType.setVisibility(View.GONE);
            tvResultTitle.setVisibility(View.GONE);
            llResultTitle.setVisibility(View.GONE);
            llReformInfo.setVisibility(View.VISIBLE);
        }

        imagesUrl=new ArrayList<>();
        managers=new GridLayoutManager(getContext(),3);
        rcPic.setLayoutManager(managers);
        adapter=new HiddenDangerImageAdapter(imagesUrl, HiddendangerUnSubmit.this);
        rcPic.setHasFixedSize(true);
        rcPic.setAdapter(adapter);
        adapter.setClickListener(new HiddenDangerImageAdapter.OnItemClickListener() {
            @Override
            public void onClick(View view, int position) {
                //添加
                PictureSelector
                        .create(HiddendangerUnSubmit.this)
                        .openGallery(PictureMimeType.ofImage())
                        .selectionMode(PictureConfig.MULTIPLE)
                        .isCamera(true)
                        .maxSelectNum(3)
                        .compressQuality(100)
                        .loadImageEngine(GlideEngine.createGlideEngine())
                        .forResult(PictureConfig.CHOOSE_REQUEST);
            }

            @Override
            public void onSelected(View view, int position) {
                switch (view.getId()){
                    case R.id.ivClear:
                        //删除当前图片
                        imagesUrl.remove(position);
                        adapter.notifyDataSetChanged();
                        break;
                }
            }
        });
    }

    public void reSetResult(){
        tvAssess.setTextColor(getResources().getColor(R.color.gray9));
        tvReform.setTextColor(getResources().getColor(R.color.gray9));
        tvReform.setBackgroundResource(R.drawable.stoke_gray_bg_5);
        tvAssess.setBackgroundResource(R.drawable.stoke_gray_bg_5);
    }

    @Override
    protected void initData() {}

    @Override
    protected int getTitleBarType() {
        return 0;
    }

    public void submitData(){


        JSONObject jsonObject=new JSONObject();
            try {
                if (!hdangerImg.equals("")) {
                    jsonObject.put("hdangerImg", hdangerImg.substring(0,hdangerImg.length()-1));
                }
                jsonObject.put("hdangerLevel",hiddendangerLevel);//隐患等级
                jsonObject.put("hdangerTitle",hdangerTitle);//隐患标题
                if (!hdangerType.equals("")){
                    jsonObject.put("hdangerType",hdangerType);//隐患类型
                }
                if (!hiddenId.equals("")){
                    jsonObject.put("hiddenId",hiddenId);
                }
                jsonObject.put("isReview",isReview);
                if (!rectImg.equals("")){
                    jsonObject.put("rectImg",rectImg);
                }

                if (!rectMeasures.equals("")){
                    jsonObject.put("rectMeasures",rectMeasures);
                }

                if (!rectPrice.equals("")){
                    jsonObject.put("rectPrice",rectPrice);
                }
                if (!rectReason.equals("")){
                    jsonObject.put("rectReason",rectReason);
                }

                if (!rectPersonId.equals("")){
                    jsonObject.put("rectPersonId",rectPersonId);
                }

                if (!rectDepartId.equals("")){
                    jsonObject.put("rectDepartId",rectDepartId);
                }

                if (!acceptDepartId.equals("")){
                    jsonObject.put("acceptDepartId",acceptDepartId);
                }

                if (!acceptPersonId.equals("")){
                    jsonObject.put("acceptPersonId",acceptPersonId);
                }
                if (!allottedTime.equals("")){
                    jsonObject.put("allottedTime",allottedTime);
                }

                if (!reviewPersonId.equals("")){
                    jsonObject.put("reviewPersonId",reviewPersonId);
                }
                if (!reviewDepartId.equals("")){
                    jsonObject.put("reviewDepartId",reviewDepartId);
                }

                 jsonObject.put("isCommit",isCommit);//是否提交 0暂存 1提交
                  jsonObject.put("reviewTime",reviewTime);
                jsonObject.put("remark",remark);//备注
                jsonObject.put("hiddenId",hiddenId);//隐患id
                jsonObject.put("riskPointId",riskPointId);
            } catch (JSONException e) {
                e.printStackTrace();
            }

        new HttpRequest(this).doPost(UrlConstants.dangercommit, "",jsonObject, new HttpStringCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSuccess(Object result) {
                String datas = result.toString();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(datas);
                    String message = jsonObject.getString("message");
                    Boolean success = jsonObject.getBoolean("success");
                    if (success) {
                        Object obj = JsonUtils.fromJson(result.toString(), BaseModel.class);
                        if (obj instanceof BaseModel) {
                            BaseModel model=(BaseModel) obj;
                            MainActivity.actionStart(HiddendangerUnSubmit.this,2);
                            finish();
                        }
                    }else {
                        Toast.makeText(HiddendangerUnSubmit.this,message,Toast.LENGTH_SHORT).show();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) {
                imagesUrl.clear();
                adapter.notifyDataSetChanged();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode==RESULT_OK){
            if (requestCode==REQUESTCODE){
                reviewDepartId=data.getStringExtra("id");
                tvAsseessDepart.setText(data.getStringExtra("name"));
            }else if(requestCode==REQUESTCODE1){
                reviewPersonId=data.getStringExtra("id");
                tvAssessPerson.setText(data.getStringExtra("name"));
            }else if(requestCode==REQUESTCODE2){
                tvHiddenLevel.setText(data.getStringExtra("name"));
                hiddendangerLevel=data.getStringExtra("type");
            }else if(requestCode==REQUESTCODE3){
                tvHiddendDangerType.setText(data.getStringExtra("name"));
                hdangerType=data.getStringExtra("id");
            } else if(requestCode==REQUESTCODE4){
                tvReformDepart.setText(data.getStringExtra("name"));
                rectDepartId=data.getStringExtra("id");
            } else if(requestCode==REQUESTCODE5){
                tvReformPerson.setText(data.getStringExtra("name"));
                rectPersonId=data.getStringExtra("id");
            } else if(requestCode==REQUESTCODE6){
                tvAcceptDepart.setText(data.getStringExtra("name"));
                acceptDepartId=data.getStringExtra("id");
            } else if(requestCode==REQUESTCODE7){
                tvAcceptPerson.setText(data.getStringExtra("name"));
                acceptPersonId=data.getStringExtra("id");
            }else if (requestCode==PictureConfig.CHOOSE_REQUEST) {
                // 结果回调 获取oss  token
                List<LocalMedia> cameraList = PictureSelector.obtainMultipleResult(data);
                imagesUrl.clear();
                for (int i = 0; i < cameraList.size(); i++) {
                    imagesUrl.add(cameraList.get(i).getRealPath());
                }
                adapter.notifyDataSetChanged();
            }
        }
    }

    public void uploadImg(String path){
        new HttpRequest(HiddendangerUnSubmit.this).doUploadFile(UrlConstants.commonupload, "", "file", new File(path), new HttpStringCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSuccess(Object result) {
                String datas = result.toString();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(datas);
                    String message = jsonObject.getString("message");
                    Boolean success = jsonObject.getBoolean("success");
                    if (success) {
                        Object obj = JsonUtils.fromJson(result.toString(), BaseModel.class);
                        if (obj instanceof BaseModel) {
                            BaseModel model=(BaseModel) obj;
                            imagesUrl.remove(0);
                            hdangerImg=hdangerImg+model.getMessage()+",";
                            Iterator<String> iterator=imagesUrl.iterator();
                            if (iterator.hasNext()){
                                uploadImg(iterator.next());
                            }else {
                                submitData();
                            }
                        }else {
                            ToastUtil toastUtil = new ToastUtil(getContext(), R.layout.popu_success1, message, 1);
                            toastUtil.show();
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) { }
        });
    }

    public void getDetail(){
        Map jsonObject=new HashMap();
        jsonObject.put("defectId",hiddenId);
        new HttpRequest(this).doGet(UrlConstants.findDefectById, null,jsonObject, new HttpStringCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSuccess(Object result) {
                String datas = result.toString();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(datas);
                    String message = jsonObject.getString("message");
                    Boolean success = jsonObject.getBoolean("success");
                    if (success) {
                        Object obj = JsonUtils.fromJson(result.toString(), HiddenDangerDetailModel.class);
                        if (obj instanceof HiddenDangerDetailModel) {
                             model=(HiddenDangerDetailModel) obj;
                             setView();
                        }
                    }else {
                        Toast.makeText(HiddendangerUnSubmit.this,message,Toast.LENGTH_SHORT).show();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) {
                Log.e("aaaa",msg);
            }
        });
    }

    public void setView(){
       riskPointId=model.getResult().getRiskPointId();
        if (model.getResult().getHdangerLevel()==1){
            tvHiddenLevel.setText("一般");
            hiddendangerLevel="3";
        }else {
            tvHiddenLevel.setText("重大");
            hiddendangerLevel="1";
        }

        if (model.getResult().getRemark()!=null&&!model.getResult().getRemark().equals("")){
            etRemark.setText(model.getResult().getRemark());
        }

        reviewDepartId=model.getResult().getReviewDepartId();
        reviewPersonId=model.getResult().getReviewPersonId();
        reviewTime=model.getResult().getAllottedTime();

        tvAsseessDepart.setText(model.getResult().getReviewDepartName());
        tvAssessPerson.setText(model.getResult().getReviewPersonName());
        tvReformDate.setText(model.getResult().getAllottedTime());
        if (model.getResult().getRectPrice()!=null&&!model.getResult().getRectPrice().equals("")){
            etPrice.setText(model.getResult().getRectPrice());
        }
        if (model.getResult().getReason()!=null&&!model.getResult().getReason().equals("")){
            etReason.setText(model.getResult().getReason());
        }
        if (model.getResult().getRectMeasures()!=null&&!model.getResult().getRectMeasures().equals("")){
            etReformMethod.setText(model.getResult().getRectMeasures());
        }
        if (model.getResult().getHdangerTitle()!=null&&!model.getResult().getHdangerTitle().equals("")){
            etHiddendDangerName.setText(model.getResult().getHdangerTitle());
        }
        tvHiddendDangerType.setText(model.getResult().getHiddenTypeName());
        hdangerType=model.getResult().getHdangerType();

        if (model.getResult().getHdangerImg()!=null&&model.getResult().getHdangerImg().length()>0){
            String [] p=model.getResult().getHdangerImg().split(",");
            for (int i=0;i<p.length;i++){
                if (p[i].length()>0&&!p[i].equals(",")){
                    imagesUrl.add(p[i]);
                }
            }
            managers=new GridLayoutManager(getContext(),3);
            rcPic.setLayoutManager(managers);
            adapter=new HiddenDangerImageAdapter(imagesUrl, HiddendangerUnSubmit.this);
            rcPic.setHasFixedSize(true);
            rcPic.setAdapter(adapter);
            adapter.setClickListener(new HiddenDangerImageAdapter.OnItemClickListener() {
                @Override
                public void onClick(View view, int position) {
                    //添加
                    PictureSelector
                            .create(HiddendangerUnSubmit.this)
                            .openGallery(PictureMimeType.ofImage())
                            .selectionMode(PictureConfig.MULTIPLE)
                            .isCamera(true)
                            .compressQuality(100)
                            .loadImageEngine(GlideEngine.createGlideEngine())
                            .forResult(PictureConfig.CHOOSE_REQUEST);
                }

                @Override
                public void onSelected(View view, int position) {
                    switch (view.getId()){
                        case R.id.ivClear:
                            //删除当前图片
                            imagesUrl.remove(position);
                            adapter.notifyDataSetChanged();
                            break;
                    }
                }
            });
        }
    }

    public void hiddenRepair(){
        Map jsonObject=new HashMap();
        jsonObject.put("hiddenId",hiddenId);

        new HttpRequest(this).doGet(UrlConstants.dangerrepeal, null,jsonObject, new HttpStringCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSuccess(Object result) {
                String datas = result.toString();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(datas);
                    String message = jsonObject.getString("message");
                    Boolean success = jsonObject.getBoolean("success");
                    if (success) {
                        Object obj = JsonUtils.fromJson(result.toString(), BaseModel.class);
                        if (obj instanceof BaseModel) {
                            BaseModel model=(BaseModel) obj;
                            finish();
                        }
                    }else {
                        Toast.makeText(HiddendangerUnSubmit.this,message,Toast.LENGTH_SHORT).show();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) { }
        });
    }
}